
const fs = require('fs');
const nunjucks = require('nunjucks');
const { SITE_ROOT, STATIC_ROOT, PAGE_SIZE } = require('../config/config');
const Service = require('../service/Service');
const service = new Service();

/**
 * 构建静态站点控制器类
 * @method buildCache() 生成缓存数据
 * @method index() 生成首页
 * @method list() 生成分类列表页
 * @method tag() 生成标签列表页
 * @method new() 生成最新列表页
 * @method recommand() 生成推荐列表页
 * @method detail() 生成详情页
 * @method search 生成搜索页
 * @method about 生成关于页
 * @method concat 生成联系页
 * @method release 生成发行页
 */
class BuildController {

    skipDirs = ['public', 'static', 'images', 'image'];

    /**
     * 生成缓存数据
     */
    async buildCache() {
        // 生成元数据文件
        await service.buildCache();
        // 复制静态资源目录（从 public 到 output）
        fs.cpSync(STATIC_ROOT, SITE_ROOT + 'static', { recursive: true });
        console.log('复制静态资源完成。');
    }

    /**
     * 生成首页
     */
    async index() {
        let viewData = await service.getIndexViewData(1, PAGE_SIZE);
        let toFilePath = SITE_ROOT + 'index.html';
        fs.writeFileSync(toFilePath, nunjucks.render('index.html', viewData));
        for (let i = 1; i <= viewData.pageCount; i++) {
            toFilePath = SITE_ROOT + 'index-' + i + '.html';
            viewData = await service.getIndexViewData(i, PAGE_SIZE);
            fs.writeFileSync(toFilePath, nunjucks.render('index.html', viewData));
        }
        console.log('[生成首页文件]', toFilePath);
    }

    /**
     * 生成分类列表页
     */
    async list() {
        let viewData = service.getViewData();
        let toDir = '', toFilePath = '', pageCount = 0, pageId = 1;
        for (let item of viewData.categories) {
            toDir = SITE_ROOT + item.name + '/';
            if (!fs.existsSync(toDir)) {
                fs.mkdirSync(toDir, { recursive: true });
            }
            pageId = 1;
            viewData = await service.getListViewDataForCategory(pageId, PAGE_SIZE, item.name, '');
            toFilePath = toDir + 'index.html';
            fs.writeFileSync(toFilePath, nunjucks.render('list.html', viewData));
            pageCount = viewData.pageCount;
            for (let i = 1; i <= pageCount; i++) {
                viewData = await service.getListViewDataForCategory(i, PAGE_SIZE, item.name, '');
                toFilePath = toDir + 'index-' + i + '.html';
                fs.writeFileSync(toFilePath, nunjucks.render('list.html', viewData));
            }
            console.log('[生成一级分类列表文件]', toFilePath);
            if (item.children) {
                for (let item2 of item.children) {
                    toDir = SITE_ROOT + `${item.name}/${item2.name}/`;
                    if (!fs.existsSync(toDir)) {
                        fs.mkdirSync(toDir, { recursive: true });
                    }
                    pageId = 1;
                    viewData = await service.getListViewDataForCategory(pageId, PAGE_SIZE, item.name, item2.name);
                    toFilePath = toDir + 'index.html';
                    fs.writeFileSync(toFilePath, nunjucks.render('list.html', viewData));
                    pageCount = viewData.pageCount;
                    for (let i = 1; i <= pageCount; i++) {
                        viewData = await service.getListViewDataForCategory(i, PAGE_SIZE, item.name, item2.name);
                        toFilePath = toDir + 'index-' + i + '.html';
                        fs.writeFileSync(toFilePath, nunjucks.render('list.html', viewData));
                    }
                    console.log('[生成二级分类列表文件]', toFilePath);
                }
            }
        }
    }

    /**
     * 生成标签列表页
     */
    async tag() {
        let viewData = service.getViewData();
        let toDir = SITE_ROOT + 'tag/', toFilePath = '', pageCount = 0, pageId = 1;
        for (let item of viewData.tags) {
            if (!fs.existsSync(toDir)) {
                fs.mkdirSync(toDir, { recursive: true });
            }
            pageId = 1;
            viewData = await service.getListViewDataForTag(pageId, PAGE_SIZE, item.title);
            toFilePath = toDir + item.title + '.html';
            fs.writeFileSync(toFilePath, nunjucks.render('list.html', viewData));
            pageCount = viewData.pageCount;
            for (let i = 1; i <= pageCount; i++) {
                viewData = await service.getListViewDataForTag(i, PAGE_SIZE, item.title);
                toFilePath = toDir + item.title + '-' + i + '.html';
                fs.writeFileSync(toFilePath, nunjucks.render('list.html', viewData));
            }
            console.log('[生成标签列表文件]', toFilePath);
        }
    }

    /**
     * 生成最新列表页
     */
    async new() {
        let toDir = SITE_ROOT, toFilePath = '', pageCount = 0, pageId = 1;
        let viewData = await service.getListViewDataForNew(pageId, PAGE_SIZE);
        toFilePath = toDir + 'new.html';
        fs.writeFileSync(toFilePath, nunjucks.render('list.html', viewData));
        pageCount = viewData.pageCount;
        for (let i = 1; i <= pageCount; i++) {
            viewData = await service.getListViewDataForNew(i, PAGE_SIZE);
            toFilePath = toDir + 'new-' + i + '.html';
            fs.writeFileSync(toFilePath, nunjucks.render('list.html', viewData));
        }
        console.log('[生成最新列表文件]', toFilePath);
    }

    /**
     * 生成推荐列表页
     */
    async recommand() {
        let toDir = SITE_ROOT, toFilePath = '', pageCount = 0, pageId = 1;
        let viewData = await service.getListViewDataForRecommand(pageId, PAGE_SIZE);
        toFilePath = toDir + 'recommand.html';
        fs.writeFileSync(toFilePath, nunjucks.render('list.html', viewData));
        pageCount = viewData.pageCount;
        for (let i = 1; i <= pageCount; i++) {
            viewData = await service.getListViewDataForRecommand(i, PAGE_SIZE);
            toFilePath = toDir + 'recommand-' + i + '.html';
            fs.writeFileSync(toFilePath, nunjucks.render('list.html', viewData));
        }
        console.log('[生成推荐列表文件]', toFilePath);
    }

    /**
     * 生成详情页
     */
    async detail() {
        let viewData = service.getViewData();
        let toDir = '', toFilePath = '', templateFilename = '';
        for (let item of viewData.categories) {
            toDir = SITE_ROOT + item.name + '/';
            if (!fs.existsSync(toDir)) {
                fs.mkdirSync(toDir, { recursive: true });
            }
            viewData = await service.getListViewDataForCategory(1, 10000, item.name, '');
            for (let fileInfo of viewData.list) {
                toFilePath = toDir + fileInfo.title + '.html';
                templateFilename = 'detail.html';
                if (fileInfo.title.includes('layui')) {
                    templateFilename = 'detail-layui.html';
                }
                fs.writeFileSync(toFilePath, nunjucks.render(templateFilename, await service.getDetailViewData(fileInfo.title, item.name, '')));
                console.log('[生成一级分类详情文件]', toFilePath);
            }
            if (item.children) {
                for await (let item2 of item.children) {
                    toDir = SITE_ROOT + `${item.name}/${item2.name}/`;
                    if (!fs.existsSync(toDir)) {
                        fs.mkdirSync(toDir, { recursive: true });
                    }
                    viewData = await service.getListViewDataForCategory(1, 10000, item.name, item2.name);
                    for (let fileInfo of viewData.list) {
                        toFilePath = toDir + fileInfo.title + '.html';
                        templateFilename = 'detail.html';
                        if (fileInfo.title.includes('layui')) {
                            templateFilename = 'detail-layui.html';
                        }
                        fs.writeFileSync(toFilePath, nunjucks.render(templateFilename, await service.getDetailViewData(fileInfo.title, item.name, item2.name)));
                        console.log('[生成二级分类详情文件]', toFilePath);
                    }
                }
            }
        }
        console.log('[生成详情文件全部完成]');
    }

    /**
     * 生成搜索页
     */
    async search() {
        let toFilePath = SITE_ROOT + 'search.html';
        fs.writeFileSync(toFilePath, nunjucks.render('search.html', service.getViewData()));
        console.log('[生成搜索文件]', toFilePath);
    }

    /**
     * 生成关于页
     */
    async about() {
        let toFilePath = SITE_ROOT + 'about.html';
        fs.writeFileSync(toFilePath, nunjucks.render('about.html', service.getViewData()));
        console.log('[生成关于文件]', toFilePath);
    }

    /**
     * 生成联系页
     */
    async concat() {
        let toFilePath = SITE_ROOT + 'concat.html';
        fs.writeFileSync(toFilePath, nunjucks.render('concat.html', service.getViewData()));
        console.log('[生成联系文件]', toFilePath);
    }

    /**
     * 生成发行页
     */
    async release() {
        let toFilePath = SITE_ROOT + 'release.html';
        fs.writeFileSync(toFilePath, nunjucks.render('release.html', service.getViewData()));
        console.log('[生成发行文件]', toFilePath);
    }

    /**
     * 生成帮助页
     */
    async help() {
        let toFilePath = SITE_ROOT + 'help.html';
        fs.writeFileSync(toFilePath, nunjucks.render('help.html', service.getViewData()));
        console.log('[生成帮助文件]', toFilePath);
    }
}

module.exports = BuildController;